package net.dgg.zz.production.suspend.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.entity.CustomerRecord;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.service.ZzWorkDayService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.MQMessageSendUtil;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.flownode.dao.ZzProductNodeFlowDao;
import net.dgg.zz.production.chargeback.dao.ZzProductOrderDao;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.ProductTimeStatus;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.dgg.zz.production.inProcess.dao.AssistantDao;
import net.dgg.zz.production.inProcess.dao.ProductOrderDao;
import net.dgg.zz.production.inProcess.dao.ProductTimeStatusDao;
import net.dgg.zz.production.inProcess.entity.Assistant;
import net.dgg.zz.production.inProcess.entity.ProductNodeFlow;
import net.dgg.zz.production.suspend.dao.SubOrderExtraDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 赵有文
 * @despriction 我的暂缓订单列表页面service
 * @create 2018/5/21 0021 下午 7:26
 **/
@Service
public class ZzSuspendedOrderService extends BaseService {
    @Autowired
    private ZzSubOrderService zzSubOrderService;
    @Autowired
    private ZzProductOrderDao zzProductOrderDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Autowired
    private ZzProductNodeFlowDao zzProductNodeFlowDao;
    @Autowired
    private ZzWorkDayService zzWorkDayService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private SubOrderExtraDao subOrderExtraDao;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private AssistantDao assistantDao;
    @Autowired
    private ProductOrderDao productOrderDao;

    public List<Map> queryMap(Map paras) {
        extraFilter(paras);
        if (null == paras.get("orderColumn")) {
            paras.put("orderDir", "desc");
            paras.put("orderColumn", "t.create_time");
        }
        return zzSubOrderService.queryMap(paras);
    }

    public int count(Map paras) {
        extraFilter(paras);
        return zzSubOrderService.count(paras);
    }

    @Transactional
    public void resumeAndRemark(Map para) {
        Map map;
        //更新子订单状态

        UserEntity user = sessionManager.getCurrentUser();
        Assert.notNull(user, "检测到当前未登录。");
        Long id = Long.valueOf(para.get("subOrderId").toString());
        ProductOrder order = productOrderDao.selectByPrimaryKey(id);
        String orderStatus="";
        if (ScProductConstant.SC_ORDER_STOP.equals(order.getStatus())){//从中止恢复生产
            orderStatus="中止恢复生产";
        }else{
            orderStatus="暂停恢复生产";
        }
        //恢复超期计算，重新计算超期
        ProductTimeStatus timeStatus = productTimeStatusDao.selectByPrimaryKey(order.getId());

        Date suspendStart = timeStatus.getStartSuspendTime();//暂缓开始时间
        if(StringUtils.isNotEmpty(suspendStart)){
            Date now = new Date();//暂缓结束时间、现在
            Long suspendTime = now.getTime() - suspendStart.getTime();//暂缓实际自然时差

            long  suspendMiniSec = 0L;
            Date nodeStartTime;
            //重新计算节点开始时间
            if(null != timeStatus.getNodeStartTime()){
                suspendMiniSec = timeStatus.getNodeStartTime().getTime()+suspendTime;
                nodeStartTime = new Date(suspendMiniSec);
            }else{
                nodeStartTime = new Date();
            }
            Integer len = 0;
            if(null != timeStatus.getNodeProcessTime() && timeStatus.getNodeProcessTime()>0){
                len = timeStatus.getNodeProcessTime();
            }else{
                len = 1;
            }
            //重新计算节点结束时间
            int type = 1;
            if(null != timeStatus.getNodeProcessTimeType()){
                type = timeStatus.getNodeProcessTimeType();
            }
            Date nodeDate = commonService.getDateFromStartByType(nodeStartTime, len, suspendTime, type);
            timeStatus.setNodeEndTime(DateUtils.getDate(DateUtils.dateString(nodeDate,"yyyy-MM-dd"),"yyyy-MM-dd"));
        }
        timeStatus.setFlag(1);
        this.updateOpt(timeStatus, user);
        productTimeStatusDao.updateByPrimaryKeySelective(timeStatus);


        order.setStatus(ScProductConstant.SC_ORDER_IN_PROCESS);
        //最新备注时间
        order.setLastRemark(para.get("remark").toString());
        order.setLastRemarkTime(new Date());
        order.setLastUser(user.getRealName()+" "+user.getLoginName());
        this.updateOpt(order, user);
        zzProductOrderDao.update(order);

        //增加流程操作记录
        //保存操作记录
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setId(DggKeyWorker.nextId());
        systemRecord.setWorkId(order.getId());
        systemRecord.setWorkTableName("zzsc_product_order");
        systemRecord.setRemarks("恢复办理:" + para.get("remark").toString());
        systemRecord.setOperateType("45");//操作类型 : 恢复办理
        systemRecord.setSource("2");//来源生产
        systemRecordService.save(systemRecord);
        try {
            //通过MQ推送消息到UC
            CustomerRecord customerRecord = new CustomerRecord();
            customerRecord.setCustomerId(order.getCustomerId());
            customerRecord.setTableName("zzsc_product_order");
            customerRecord.setTableId(order.getId());
            customerRecord.setTableNo(order.getScProductOrderNo());
            customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE6);
            customerRecord.setCreaterId(user.getId());
            if (StringUtils.isNotEmpty(para.get("remark"))){
                customerRecord.setContent(para.get("remark").toString());
            }
            MQMessageSendUtil.ucMessageSend(customerRecord);
            //提交之后，将订单信息同步到企大顺生产中心
            MQMessageSendUtil.qdsMessageSend(order, null,  user);
        }catch (Exception e){
            e.printStackTrace();
        }
        //向企管家发送生产暂停消息
        String msgConent="您好，您的客户"+order.getCustomerName()+"订单"+order.getOrderNo()+"办理的"+order.getScProductOrderNo()+"业务，订单"+orderStatus+",请及时确认处理";
        commonService.sendQgjMessage(order.getOrderId(),order.getBusinessTypeCode(),user.getId(),user.getRealName(),user.getLoginName(),msgConent);
    }

    /**
     * 处理参数
     *
     * @param paras
     */
    private void extraFilter(Map paras) {
        paras.put("status", ScProductConstant.SC_ORDER_SUSPEND);
        paras.put("dataAuthority", "zzsc_sc_suspend");
    }

    /**
    * <p>@Description 团队生产暂停页面数据</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/28 0028 15:32 创建时间</p>
    * <p>@return</p>
    */
    public List<Map> teamSuspendOrderPageData(Map paras) {
        paras.put("status", ScProductConstant.SC_ORDER_SUSPEND);
        paras.put("dataAuthority", "zzsc_sc_suspend");
        UserEntity userEntity = sessionManager.getCurrentUser();
        List<Long> orgIdList =commonMangerExtService.getChildOrganizationList(userEntity.getOrgId());
        paras.put("orgIdList", orgIdList);//获取本部门以及下属部门
        List<Map> resultList = subOrderExtraDao.queryMap(paras);
        return resultList;
    }

    public boolean isDo(Long id){

        UserEntity userEntity = sessionManager.getCurrentUser();
        ProductOrder order = zzProductOrderDao.getById(id);
        List<Assistant> assistantList = assistantDao.query(new HashMap<String, Object>() {{
            put("scProductOrderId", order.getId());
            put("assistUserId", userEntity.getId());
        }});
        if(assistantList.size() > 0) {
            if (null != order.getProductUserId()) {
                if (userEntity.getId().toString().equals(order.getProductUserId().toString())) {
                    return true;
                }
            }
            if (null != order.getFlowUserId()) {
                if (userEntity.getId().toString().equals(order.getFlowUserId().toString())) {
                    return true;
                }
            }
        }else{
            return true;
        }
        return false;
    }
}

